import { _decorator, Component, instantiate, Prefab, Node, Widget, UITransform, Vec3, Label } from "cc";
import { EventEnum, PrefabPathEnum } from "../Enum";
import { ResourceManager } from "../utils/ResourceManager";
import DataManager from "../global/DataManager";
import { EntityTypeEnum, ICard, ISeat } from "../common";
import { Card } from "../Card";
import { CardTemplate } from "../CardTemplate";
import { Seat } from "../Seat";
import EventManager from "../manages/EventManager";
const { ccclass, property } = _decorator;
@ccclass('MahjongManager')
export class MahjongManager extends Component {


    seats: ISeat[] = [
        {
            dirction: 0,
            id: 1,
            playerId: 1,
            // node: null,
        },
        {
            dirction: 1,
            id: 2,
            playerId: 2,
            // node: null,

        },
        {
            dirction: 2,
            id: 3,
            playerId: 3,
            // node: null,

        },
        {
            dirction: 3,
            id: 4,
            playerId: 4,
            // node: null,

        },
    ]

    cardNodes: Node[] = [];

    throwingSieveBtn: Node;
    sieves: number[];

    catchFlowerCardStackIndex: number;
    catchFlowerCardIndex: number;
    catchCardIndex: number;
    catchCardStackIndex: number;
    currentActiveDirection: number; // 当前行动对象的方位

    fristSeat: ISeat;  // 第一视角的座位 即[我]的座位


    async onLoad() {
        DataManager.Instance.mm = this
        this.throwingSieveBtn = this.node.getChildByName("Btn")
        this.throwingSieveBtn.active = DataManager.Instance.lastWinerDirction == DataManager.Instance.myDirction
        this.fristSeat = this.seats.find(s => s.playerId == DataManager.Instance.myPlayerId)
        await this.loadRes();
        this.createSeat()
        this.init()
        this.shuffleArray()
        this.splitArray(this.cardNodes)
        this.currentActiveDirection = DataManager.Instance.lastWinerDirction
        EventManager.Instance.on(EventEnum.TurnStart, this.turnStartHandle, this)
        EventManager.Instance.on(EventEnum.TurnEnd, this.turnEndHandle, this)
    }

    onDestroy() {
        EventManager.Instance.off(EventEnum.TurnStart, this.turnStartHandle, this)
        EventManager.Instance.off(EventEnum.TurnEnd, this.turnEndHandle, this)
    }
    // 回合开始
    turnStartHandle() {

        // const seat = this.seats.find(e => e.dirction == this.currentActiveDirection).node.getComponent(Seat)
        // const seat 
        this.node.children.forEach(item => {
            if (item.getComponent(Seat)) {

            }

        })
        const seat = this.node.children.find((e) => {
            if (e.getComponent(Seat)) {
                return e.getComponent(Seat).direction == this.currentActiveDirection
            }
        })
        seat.getComponent(Seat).roundAction()

    }
    // 回合结束
    turnEndHandle() {
        this.currentActiveDirection++
        if (this.currentActiveDirection >= 3) this.currentActiveDirection = 0
        EventManager.Instance.emit(EventEnum.TurnStart)
    }


    async loadRes() {
        const pList = []
        for (const type in PrefabPathEnum) {
            const p = ResourceManager.Instance.loadRes(PrefabPathEnum[type], Prefab).then((prefab) => {
                DataManager.Instance.prefabMap.set(type, prefab)
            })
            pList.push(p)
        }
        await Promise.all(pList)

    }

    // 生成麻将
    init() {
        let id = 0;
        const types: Array<String> = ['wan', 'tong', 'tiao', 'feng', 'zhongfabai', 'hongheihua']
        const cards: Array<ICard> = []
        for (let j = 0; j < 3; j++) {
            for (let index = 0; index < 9; index++) {
                for (let i = 0; i < 4; i++) {
                    const iCard: ICard = {
                        id: id,

                        type: types[j], //wan tong tiao feng zhongfabai hongheihua

                        index: index + 1,

                        state: 0,
                    }
                    cards.push(iCard);

                    id++;
                }
            }
        }
        for (let index = 0; index < 4; index++) {
            for (let i = 0; i < 4; i++) {
                const iCard: ICard = {
                    id: id,

                    type: types[3], //wan tong tiao feng zhongfabai hongheihua

                    index: index + 1,

                    state: 0,
                }
                cards.push(iCard);
                id++;
            }
        }
        for (let index = 0; index < 3; index++) {
            for (let i = 0; i < 4; i++) {
                const iCard: ICard = {
                    id: id,

                    type: types[4], //wan tong tiao feng zhongfabai hongheihua

                    index: index + 1,

                    state: 0,
                }
                cards.push(iCard);
                id++;
            }
        }
        for (let index = 0; index < 8; index++) {
            const iCard: ICard = {
                id: id,

                type: types[5], //wan tong tiao feng zhongfabai hongheihua

                index: index + 1,

                state: 0,
            }
            cards.push(iCard);

            id++;
        }

        for (let index = 0; index < cards.length; index++) {
            const prefab = DataManager.Instance.prefabMap.get(EntityTypeEnum.Card)
            const card = instantiate(prefab)
            const data = cards[index];
            this.cardNodes.push(card)
            card.getComponent(CardTemplate).init(data)

        }

    }

    // 洗牌  打乱顺序
    shuffleArray() {
        for (let i = this.cardNodes.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.cardNodes[i], this.cardNodes[j]] = [this.cardNodes[j], this.cardNodes[i]];
        }

    }
    // 发牌
    splitArray(arr) {
        var result = [];
        const temArr = [...arr]
        for (var i = 0; i < temArr.length; i += 36) {
            var chunk = temArr.slice(i, i + 36);

            result.push(chunk);
        }

        for (let index = 0; index < this.seats.length; index++) {
            const seatId: number = this.seats[index].id;
            const seat = this.node.children.find(e => {
                if (e.getComponent(Seat) && e.getComponent(Seat).id == seatId) {
                    return e;
                }
            }).getComponent(Seat)



            for (let j = 0; j < result[index].length; j++) {

                seat.head.addChild(result[index][j])
            }



        }


    }


    createSeat() {
        let dirction = DataManager.Instance.myDirction;

        for (let index = 0; index < this.seats.length; index++) {
            const seat = this.seats[index];
            const prefab = DataManager.Instance.prefabMap.get(EntityTypeEnum.Seat)
            const seatPre = instantiate(prefab)
            seatPre.getComponent(Seat).init(seat)

            seatPre.setParent(this.node)
            if (seat.dirction != dirction) {
                seatPre.setRotationFromEuler(0, 0, -90 * (dirction - seat.dirction))
                seatPre.getChildByName("action-collection").active = false


            }
            switch (seat.dirction - dirction) {
                case 0:
                    seatPre.position = new Vec3(0, -180, 0)
                    break;
                case 1:
                    seatPre.position = new Vec3(460, 0, 0)
                    break;
                case 2:
                    seatPre.position = new Vec3(0, 180, 0)
                    break;
                case 3:
                    seatPre.position = new Vec3(-460, 0, 0)
                    break;

            }
            const players = DataManager.Instance.state.players;
            const player = players.find(e => seat.playerId == e.id)
            const label = seatPre.getComponentInChildren(Label)
            label.string = player.username + " " + player.sorce

        }

    }

    /**
  * 
  * @param index ; 开始抓牌的人
  * @param count; 一次性抓牌的数量
  * @returns 
  */
    RoundStartDraw(index: number, count: number) {
        return new Promise<void>((resolve) => {
            setTimeout(() => {
                const seatId: number = this.seats[index].id;
                const seat = this.node.children.find(e => {
                    if (e.getComponent(Seat) && e.getComponent(Seat).id == seatId) {
                        return e;
                    }
                }).getComponent(Seat)
                for (let i = 0; i < count; i++) {
                    seat.getComponent(Seat).grabHandCard()
                }
                resolve()
            }, 500)
        })

    }



    // 开始抓牌
    async startDraw() {
        const sieves = this.sieves
        const sum = sieves[0] + sieves[1] - 1
        this.catchFlowerCardStackIndex = sum % 4;
        this.catchFlowerCardIndex = 35 - Math.min(sieves[0], sieves[1]) * 2;
        this.catchCardIndex = 35 - Math.min(sieves[0], sieves[1]) * 2
        this.catchCardStackIndex = sum % 4;
        let startDrawSeatIndex = DataManager.Instance.lastWinerDirction;

        for (let i = 0; i < 17; i++) {
            const count = i < 12 ? 4 : 1
            await this.RoundStartDraw(startDrawSeatIndex, count);
            startDrawSeatIndex++;
            if (startDrawSeatIndex > 3) startDrawSeatIndex = 0;
        }

        //  手牌排序
        for (let i = 0; i < 4; i++) {

            const seatId: number = this.seats[i].id;
            const seat = this.node.children.find(e => {
                if (e.getComponent(Seat) && e.getComponent(Seat).id == seatId) {
                    return e;
                }
            })
            const hand = seat.getChildByName("hand")
            const action = seat.getChildByName("action")
            // 复制 数据排序
            const arr = [...hand.children]

            arr.sort((a, b) => {

                return a.getComponent(CardTemplate).id - b.getComponent(CardTemplate).id
            })
            //
            let hua = []  // 筛选 [花]
            // 重置索引
            for (let index = 0; index < arr.length; index++) {
                const node = arr[index];
                if (node.getComponent(CardTemplate).id > 123) {
                    hua.push(node)
                }
                node.setSiblingIndex(index)
            }

            for (let index = 0; index < hua.length; index++) {
                const node = hua[index];
                node.setParent(action)
                node.getComponent(CardTemplate).state = 3

                node.getComponent(CardTemplate).updateCardSpriteFrame()
            }

        }
        EventManager.Instance.emit(EventEnum.TurnStart)


        // this.currentActiveDirection = DataManager.Instance.lastWinerDirction
        // const seat = this.seats.find(e => e.dirction == this.currentActiveDirection).node.getComponent(Seat)
        // seat.roundAction()


    }



    /**
     * 
     * @param i 0  1  2  3 
     * @param startStack  抓取谁的牌堆
     * @param index 抓取牌的索引
     */
    // grad(i: number, startStack: Node, index: number) {
    //     const seat: Node = this.seats[i].node
    //     const node = [...startStack.children][index]
    //     const cardTemplate: CardTemplate = node.getComponent(CardTemplate)
    //     cardTemplate.state = 1
    //     switch (i) {
    //         case 0:
    //             cardTemplate.directionInFrist = 'self'
    //             break;
    //         case 1:
    //             cardTemplate.directionInFrist = 'after'
    //             break;
    //         case 2:
    //             cardTemplate.directionInFrist = 'face'
    //             break;
    //         case 3:
    //             cardTemplate.directionInFrist = 'font'
    //             break;
    //     }
    //     seat.getComponent(Seat).grabHandCard(node)
    //     const newNode = new Node("");
    //     const ui = node.getComponent(UITransform)
    //     newNode.addComponent(UITransform);
    //     newNode.getComponent(UITransform).width = ui.width
    //     newNode.getComponent(UITransform).height = ui.height

    //     startStack.insertChild(newNode, index)


    // }



}

